import ReactDOM from "react-dom";
import { Component } from "react";
import './index.css'

/* 
  1. 展示评论列表功能
    1.1 通过state提供评论列表的数据
    1.2 通过map可以动态的渲染
  2. 清空评论的功能
  3. 发表新的评论功能
  4. 删除评论功能
  5. 没有更多评论的处理

*/

class Comment extends Component {
    state = {
        name: '',
        context: '',
        com: [{
            id: 1,
            name: 'zd',
            context: '11'
        },
        {
            id: 2,
            name: 'li',
            context: '22'
        },
        {
            id: 3,
            name: 'wa',
            context: '33'
        },
        {
            id: 4,
            name: 'ma',
            context: '44'
        },
        ]
    }
    render() {
        return (
            <div className="app">
                <div>
                    <input className="user" type='text' placeholder='请输入评论人' value={this.state.name} onChange={this.handleChange} name='name'></input>
                    <br />
                    <textarea className="content" cols="30" rows='10' placeholder="请输入评论内容" value={this.state.context} onChange={this.handleChange} name='context'></textarea>
                    <br />
                    <button onClick={this.addCom}>发表评论</button>
                    <button onClick={this.clear}>清空评论</button>
                    <ul>
                        {this.state.com.map((item) => {
                            return (
                                <li key={item.id}>
                                    <h3>评论人：{item.name}</h3>
                                    <p>评论内容：{item.context}</p>
                                    <button onClick={() => this.del(item.id)}>删除</button>
                                </li>

                            )
                        })}

                    </ul>
                </div>
            </div>
        )
    }
    handleChange = (e) => {
        const { name, value } = e.target
        this.setState({
            [name]: value
        })
    }
    addCom = () => {
        const { com, context, name } = this.state
        if (!context || !name) {
            return alert('填写信息不完整')
        }
        this.setState({
            com: [{ id: Date.now(), name, context }, ...com],
            name: '',
            context: "",
        })
    }
    del = (id) => {
        console.log(id)
        this.setState({
            com: this.state.com.filter((item) => item.id !== id)
        })
    }

    clear = () => {
        this.setState({
            com: []
        })
    }

}

ReactDOM.render(<Comment />, document.getElementById('root'))